package com.ruoyi.app.controller;

import com.ruoyi.app.domain.AppUser;
import com.ruoyi.app.service.IAppUserService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

/**
 * @Description: 用户登录 Controller
 * @Author: mlk
 * @Date: 2024/11/29 18:10
 */
@RestController
@RequestMapping("/api/appUser")
public class UserController {


    @Autowired
    private TokenService tokenService;

    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 根据手机号获取 AppUser 登录信息
     */
    @GetMapping(value = "/{phone}")
    public AjaxResult getAppUser(@PathVariable("phone") String phone) {
        AjaxResult ajax = AjaxResult.success();
        // 设置一下登录时间
        // 无论是手机号校验，还是账号密码校验，如果为true，走底下的createToken方法
        HashMap res = appUserService.getLoginInfo(phone);
        if ((boolean)res.get("isLogin") == true) {
            LoginUser loginBody = (LoginUser) res.get("loginBody");
            loginBody.setLoginTime(new Date().getTime());
            String token = tokenService.createToken(loginBody);
            ajax.put(Constants.TOKEN, token);
            ajax.put("appUser", res.get("appUser"));
            return ajax;
        } else {
            return AjaxResult.error((String) res.get("msg"));
        }
    }

    /**
     * 修改appUser
     */
    // @Log(title = "appUser", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppUser appUser) {
        return AjaxResult.success(appUserService.updateAppUser(appUser));
    }

    /**
     * 获取appUser详细信息
     */
    // @PreAuthorize("@ss.hasPermi('app:appUser:query')")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(appUserService.selectAppUserById(id));
    }
}
